/*
 *   Copyright 2021 zzh
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 */

package com.aduib.boot.logging.operation.handler;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ArrayUtil;
import com.aduib.boot.common.json.DefaultJsonParser;
import com.aduib.boot.common.json.JsonParser;
import com.aduib.boot.common.log.LOG;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: AbstractOpLogHandler
 * @author: zzh
 * @date: 2021/9/17 10:50
 */
public abstract class AbstractOpLogHandler<T> implements OpLogHandler<T>{

  private JsonParser jsonParser;
  /**
   * 记录忽略的参数类型列表
   */
  private final List<Class<?>> ignoreParamClasss = ListUtil.toList(HttpServletRequest.class,
      HttpServletResponse.class, MultipartFile.class);

  public AbstractOpLogHandler() {
    this.jsonParser=DefaultJsonParser.build();
  }

  public AbstractOpLogHandler(JsonParser jsonParser) {
    this.jsonParser = jsonParser;
  }

  public void addParamClass(Class<?> clazz){
    ignoreParamClasss.add(clazz);
  }

  public String getParameters(ProceedingJoinPoint joinPoint){
    // 获取方法签名
    Signature signature = joinPoint.getSignature();
    String strClassName = joinPoint.getTarget().getClass().getName();
    String strMethodName = signature.getName();
    MethodSignature methodSignature = (MethodSignature) signature;
    LOG.d("[OpLog]，获取方法参数[类名]:{},[方法]:{}", strClassName, strMethodName);

    String[] parameterNames = methodSignature.getParameterNames();
    Object[] args = joinPoint.getArgs();
    if (ArrayUtil.isEmpty(parameterNames)) {
      return null;
    }
    Map<String, Object> paramsMap = new HashMap<>();
    for (int i = 0; i < parameterNames.length; i++) {
      Object arg = args[i];
      if (arg == null) {
        paramsMap.put(parameterNames[i], null);
        continue;
      }
      Class<?> argClass = arg.getClass();
      // 忽略部分类型的参数记录
      for (Class<?> ignoredParamClass : ignoreParamClasss) {
        if (ignoredParamClass.isAssignableFrom(argClass)) {
          arg = "ignored param type: " + argClass;
          break;
        }
      }
      paramsMap.put(parameterNames[i], arg);
    }

    String params = "";
    try {
      params = jsonParser.write(paramsMap);
    }
    catch (Exception e) {
      LOG.e("[OpLog]，获取方法参数异常，[类名]:{},[方法]:{}", strClassName, strMethodName, e);
    }

    return params;
  }
}
